/*
 * (C) Copyright 2003
 * Texas Instruments <www.ti.com>
 *
 * (C) Copyright 2002
 * Sysgo Real-Time Solutions, GmbH <www.elinos.com>
 * Marius Groeger <mgroeger@sysgo.de>
 *
 * (C) Copyright 2002
 * Sysgo Real-Time Solutions, GmbH <www.elinos.com>
 * Alex Zuepke <azu@sysgo.de>
 *
 * (C) Copyright 2002-2004
 * Gary Jennejohn, DENX Software Engineering, <garyj@denx.de>
 *
 * (C) Copyright 2004
 * Philippe Robin, ARM Ltd. <philippe.robin@arm.com>
 *
 * Copyright (C) 2007 Sergey Kubushyn <ksi@koi8.net>
 *
 * See file CREDITS for list of people who contributed to this
 * project.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 * MA 02111-1307 USA
 */

#include "dm368.h"
#include "rtthread.h"
#include "system_clock.h"

typedef volatile struct 
{
	rt_uint32_t	pid12;
	rt_uint32_t	emumgt;
	rt_uint32_t	reserved_1;
	rt_uint32_t	reserved_2;
	rt_uint32_t	tim12;
	rt_uint32_t	tim34;
	rt_uint32_t	prd12;
	rt_uint32_t	prd34;
	rt_uint32_t	tcr;
	rt_uint32_t	tgcr;
	rt_uint32_t	wdtcr;
} davinci_timer;

davinci_timer *system_timer = (davinci_timer *)DM368_BASE_TIMER0;

#define TIM_CLK_DIV	16

/**
 * This function will handle rtos timer
 */
void rt_timer_handler(int vector)
{
	rt_tick_increase();
	rt_hw_interrupt_ack(IRQ_TINT0_TINT34);
}

void rt_hw_timer_init(void)
{
	/* We are using timer0_34 in unchained 32-bit mode, full speed */
	system_timer->tcr = 0x0; //use internal clock(PLL1/4)
	system_timer->tgcr = 0x0;
	system_timer->tgcr = 0x06 | ((TIM_CLK_DIV - 1) << 8);
	system_timer->tim34 = 0x0;
	system_timer->prd34 = davinci_timer0_clk_get()/(RT_TICK_PER_SECOND*TIM_CLK_DIV); //TIMER LOAD VALUE
	system_timer->tcr = 2 << 22; //ENAMODE34 - 2h The timer is enabled continuously

	rt_hw_interrupt_install(IRQ_TINT0_TINT34, rt_timer_handler, RT_NULL);
	rt_hw_interrupt_umask(IRQ_TINT0_TINT34);
}

void reset_timer(void)
{
	system_timer->tcr = 0x0;
	system_timer->tim34 = 0;
	system_timer->prd34 = davinci_timer0_clk_get()/(TIM_CLK_DIV*RT_TICK_PER_SECOND); //TIMER LOAD VALUE
	system_timer->tcr = 2 << 22;
}
